
var appId = 'wx91e8b20a8fce5f03';
//var appId = 'wxed7380181619ea73';
var hostUrl = "http://testmidu.readerday.com/api/v2/";
// var hostUrl = "https://apiv2.readerday.com/api/v2/";
// var shareUrl = "http://testwx2.readerday.com/";
var shareUrl = "http://testwxmidu.readerday.com/";
var imgHosturl = "http://img.readerday.com/cover/";
var imgFaceurl = "http://img.readerday.com/face/";
var slogenFont = ["蜜读 | 解读全球经典好书","蜜读 | 传播全人类共有的知识和观点","蜜读 | 书,是人生的第一滴蜜","蜜读 | 名师解读,30分钟即可阅读一本书","蜜读 | 留存全书精髓,过滤90%的无效信息","蜜读 | 严选国内外经典好书,告别低质阅读","蜜读 | 帮你化繁为简,降低阅读难度"]
var weixinData =null;
var userId = window.sessionStorage.getItem("userId");
var unionid = window.sessionStorage.getItem("unionid");
var token = window.sessionStorage.getItem("token");
token = token ? token : "0";
var userVip = window.sessionStorage.getItem("userVip");
userVip=userVip?JSON.parse(userVip):{};
var splitCode = "?code".indexOf(window.location.href)==-1 ? "&code" : "?code";
var relink = shareUrl + "auth.html?url="+encodeURIComponent(window.location.href.split(splitCode)[0])




function getToken(fn){
    $.ajax({
        url: hostUrl+"other/jssgin2?url="+encodeURIComponent(window.location.href),
        dataType: "json",
        success: function (data) {
            var shareData = {};
            shareData.share = data.data;
            after(shareData);
        }
    });

    if(!!!window.sessionStorage.getItem("userId")){
        var urlData = $.url().param();
        var Acode;

            if(typeof urlData.code == 'string' ){
                Acode = urlData.code;
            }else{
                Acode = urlData.code[urlData.code.length-1];
            }



        $.ajax({
            type: 'post',
            url: hostUrl+"wechat/login2",
            data: {
                code: Acode,
                url : location.href.split('#')[0]
            },
            async:false,
            dataType: 'json',
            success: function (data) {
                window.sessionStorage.setItem("weixinData",JSON.stringify(data));
                userId = data.data.userInfo.userid;
                unionid = data.data.userInfo.unionId;
                token = data.data.userInfo.token;
                userVip=data.data.userInfo.vip||{};
                if(userVip.type==1){
                    userVip.freeType=1;
                }
                if(userVip.expire_time){
                    if(new Date(userVip.expire_time).getTime()-new Date().getTime()<0){
                        userVip.type=-1;//-1是到期
                    }else{
                        userVip.type=1;
                    }
                }
                console.log(data.data.userInfo)
                window.sessionStorage.setItem("userVip",JSON.stringify(userVip));
                window.sessionStorage.setItem("unionid",data.data.userInfo.unionId);
                window.sessionStorage.setItem("userId",data.data.userInfo.userid);
                window.sessionStorage.setItem("token",data.data.userInfo.token);
                window.sessionStorage.setItem("subscribe",data.data.userInfo.subscribe);
                //交换token
                fn();
            },
            error: function () {
                console.info('ajax登录调用出错了');
            }
        });
    }else{
        userId = window.sessionStorage.getItem("userId");
        unionid = window.sessionStorage.getItem("unionid");
        token = window.sessionStorage.getItem("token");
        if (userVip.expire_time) {
            if(new Date(userVip.expire_time).getTime()-new Date().getTime()<0){
                userVip.type=-1;//到期
            }else{
                userVip.type=1;
            }
        }
        fn();
    }
}



function after(dat){
    wx.config({
        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        appId: dat.share.appId+'', // 必填，公众号的唯一标识
        timestamp: dat.share.timestamp, // 必填，生成签名的时间戳
        nonceStr: dat.share.nonceStr+'', // 必填，生成签名的随机串
        signature: dat.share.signature+'',// 必填，签名，见附录1
        jsApiList : [
            'checkJsApi', 'onMenuShareTimeline',
            'onMenuShareAppMessage', 'onMenuShareQQ',
            'onMenuShareWeibo', 'hideMenuItems',
            'showMenuItems', 'hideAllNonBaseMenuItem',
            'showAllNonBaseMenuItem', 'translateVoice',
            'startRecord', 'stopRecord', 'onRecordEnd',
            'playVoice', 'pauseVoice', 'stopVoice',
            'uploadVoice', 'downloadVoice', 'chooseImage',
            'previewImage', 'uploadImage', 'downloadImage',
            'getNetworkType', 'openLocation', 'getLocation',
            'hideOptionMenu', 'showOptionMenu', 'closeWindow',
            'scanQRCode', 'chooseWXPay',
            'openProductSpecificView', 'addCard', 'chooseCard',
            'openCard'
        ]
    });
}
//	    merchant_id
function payClick(da,type,product_id,isCloseCurrentPage,merchant_id,unionid2,backFunc) {
    var reqData={
        "channel":'weixin',
        "type": type,
        "openId": da.data.userInfo.openId,
        "unionId": da.data.userInfo.unionId,
        "client_ip":da.data.ip,
        "product_id": product_id,
    };
    if (merchant_id) {
        reqData.merchant_id=merchant_id
    }

    if(unionid2){
        reqData.unionid2=unionid2
    }
    $.ajax({
        url: hostUrl+"miduwxpay/wxwebsave",
        type: "post",
        data:reqData,
        dataType: "json",
        success: function (data) {
            if (data.status == 0) {
                var att = data.data;
                pay(att.timeStamp, att.nonceStr, att.package, att.paySign, att.orderno,isCloseCurrentPage,type,backFunc);
            } else {
                alert(data.message);
            }
        },
        error: function () {
            alert("出错了");
        }
    });
}

function pay(timeStamp, nonceStr, package, paySign, orderno,isCloseCurrentPage,type,backFunc) {
    wx.chooseWXPay({
        timestamp: timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
        nonceStr: '' + nonceStr + '', // 支付签名随机串，不长于 32 位
        package: '' + package + '', // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
        signType: 'MD5', // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
        paySign: '' + paySign + '', // 支付签名
        success: function (res) {
            // 支付成功后的回调函数
            $.ajax({
                url: hostUrl+"miduwxpay/findByNo",
                type: "post",
                data: {
                    "orderNo": "" + orderno + ""
                },
                dataType: "json",
                success: function (data) {
                    if (data.status == 0) {
//		                            var timestamp = new Date().getTime();

                        if(type==7){
                            backFunc();
                            return;
                        }
                        if(isCloseCurrentPage){                //主题包试读页面的购买
                            if(window.sessionStorage.getItem("hasSubscribe")=="false"){
                                window.sessionStorage.setItem("type","1")     //未关注公众号购买后刷新需要弹出二维码
                                history.go(-1);
                            }
                            history.go(-1);
                        }else{
                            if(window.sessionStorage.getItem("hasSubscribe")=="false"){
                                window.sessionStorage.setItem("type","1")     //未关注公众号购买后刷新需要弹出二维码
                                location.reload();
                            }
                            location.reload();
                        }
                        //会员支付完成

                    } else {
                        alert(data.message);
                    }
                }
            });
        },
        cancel: function (res) {

        }
    });
}

function shareWx(title,img,desc){
    var titleStr;
    var bookid;
    var stage;
    var imgUrl;
    var imgStr = img.substring(0,4);
    if (imgStr == "http") {
        imgUrl = img;
    } else{
        imgUrl = imgHosturl + img;
    }
    var arr = title.split('key=');
    if (arr.length > 1) {
        titleStr = arr[0];
        bookid = arr[1];
        stage = arr[2];
    } else{
        titleStr = title;
    }
    wx.ready(function () {
        //分享朋友圈
        wx.onMenuShareTimeline({
            title: titleStr,
            link: relink,
            imgUrl: imgUrl,// 自定义图标
            trigger: function (res) {
                // 不要尝试在trigger中使用ajax异步请求修改本次分享的内容，因为客户端分享操作是一个同步操作，这时候使用ajax的回包会还没有返回.
                //alert('click shared');
            },
            success: function (res) {
                MtaH5.clickStat("share_button")//用户点击右上角分享按钮
                MtaH5.clickShare('wechat_moments');//统计朋友圈分享
                if (bookid) {
                    if (window.localStorage) {
                        localStorage.setItem('share_activity' ,bookid + "_" + stage);
                    } else{
                        setCookie('share_activity' ,bookid + "_" + stage);
                    }
                    $.ajax({
                        type:"get",
                        url:hostUrl + "statistics/giveone?channel=weixin&unionid=" + unionid + "&bookid=" + bookid,
                        async:true
                    });
                }
            },
            cancel: function (res) {
                //alert('shared cancle');
            },
            fail: function (res) {
                //alert(JSON.stringify(res));
            }
        });
        //分享到QQ
        wx.onMenuShareQQ({
            title: titleStr,
            desc: desc, // 分享描述
            link: relink,
            imgUrl: imgUrl,// 自定义图标
            type: 'link', // 分享类型,music、video或link，不填默认为link
            dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
            success: function () {
                MtaH5.clickStat("share_button")//用户点击右上角分享按钮
                if (bookid) {
                    if (window.localStorage) {
                        localStorage.setItem('share_activity' ,bookid + "_" + stage);
                    } else{
                        setCookie('share_activity' ,bookid + "_" + stage);
                    }
                    $.ajax({
                        type:"get",
                        url:hostUrl + "statistics/giveone?channel=weixin&unionid=" + unionid + "&bookid=" + bookid,
                        async:true
                    });
                }
            },
            cancel: function () {
                // 用户取消分享后执行的回调函数
            }
        });
        //分享给好友
        wx.onMenuShareAppMessage({
            title: titleStr,
            desc: desc, // 分享描述
            link: relink,
            imgUrl: imgUrl,// 自定义图标
            type: 'link', // 分享类型,music、video或link，不填默认为link
            dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
            success: function () {
                MtaH5.clickStat("share_button")//用户点击右上角分享按钮
                MtaH5.clickShare('wechat_friend');//统计分享微信好友
                MtaH5.clickStat('haoyouzhulimian',{'sharebutton':'true'})//漏斗统计
                if (bookid) {
                    if (window.localStorage) {
                        localStorage.setItem('share_activity' ,bookid + "_" + stage);
                    } else{
                        setCookie('share_activity' ,bookid + "_" + stage);
                    }
                    $.ajax({
                        type:"get",
                        url:hostUrl + "statistics/giveone?channel=weixin&unionid=" + unionid + "&bookid=" + bookid,
                        async:true
                    });
                }
            },
            cancel: function () {
                // 用户取消分享后执行的回调函数
            }
        });
        wx.error(function (res) {
            alert(res.errMsg);
        });
    });
}

function setCookie(name, value) {
    var argv = setCookie.arguments;
    var argc = setCookie.arguments.length;
    var expires = (argc > 2) ? argv[2] : null;
    if (expires!=null) {
        var LargeExpDate = new Date ();
        LargeExpDate.setTime(LargeExpDate.getTime() + (expires*1000*3600*24));
    }
    document.cookie = name + "=" + escape (value)+((expires == null) ? "" : ("; expires=" +LargeExpDate.toGMTString()));
}

function ascli(url){
    var param = url.split("?")[1].split("&");
    param.sort();
    str = param.join("&")+"&key=wwdxreaderwhat0823";
    return url+"&sign="+hex_md5(str).toUpperCase();
}
function rand(min,max){
    return parseInt(Math.random()*(max-min))+min;
}
function formatSeconds(a) {
    var hh = parseInt(a/3600);
    if(hh >0 && hh <10){hh = "0" + hh;}
    else {
        hh = '';
    }
    var mm = parseInt((a-hh*3600)/60);
    if(mm<10) mm = "0" + mm;
    var ss = parseInt((a-hh*3600)%60);
    if(ss<10) ss = "0" + ss;
    var length = hh.length?(hh + ":" + mm + ":" + ss):mm + ":" + ss;
    if(a>0){
        return length;
    }else{
        return "NaN";
    }
}

Date.prototype.Format = function(formatStr) {
    var str = formatStr;
    var Week = [ '日', '一', '二', '三', '四', '五', '六' ];

    str = str.replace(/yyyy|YYYY/, this.getFullYear());
    str = str.replace(/yy|YY/,(this.getYear() % 100) > 9 ? (this.getYear() % 100).toString() : '0' + (this.getYear() % 100));

    str = str.replace(/MM/, (this.getMonth() + 1) > 9 ? (this.getMonth() + 1).toString() : '0' + (this.getMonth() + 1));
    str = str.replace(/M/g, this.getMonth());

    str = str.replace(/w|W/g, Week[this.getDay()]);

    str = str.replace(/dd|DD/, this.getDate() > 9 ? this.getDate().toString() : '0' + this.getDate());
    str = str.replace(/d|D/g, this.getDate());

    str = str.replace(/hh|HH/, this.getHours() > 9 ? this.getHours().toString() : '0' + this.getHours());
    str = str.replace(/h|H/g, this.getHours());
    str = str.replace(/mm/, this.getMinutes() > 9 ? this.getMinutes().toString() : '0' + this.getMinutes());
    str = str.replace(/m/g, this.getMinutes());

    str = str.replace(/ss|SS/, this.getSeconds() > 9 ? this.getSeconds().toString() : '0' + this.getSeconds());
    str = str.replace(/s|S/g, this.getSeconds());

    return str;
}

function setCookie(c_name,value,expiredays){
    var exdate=new Date()
    exdate.setDate(exdate.getDate()+expiredays)
    document.cookie=c_name+ "=" +escape(value)+
        ((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
}

//取回cookie
function getCookie(c_name){
    if (document.cookie.length>0){
        c_start=document.cookie.indexOf(c_name + "=")
        if (c_start!=-1){
            c_start=c_start + c_name.length+1
            c_end=document.cookie.indexOf(";",c_start)
            if (c_end==-1) c_end=document.cookie.length
            return unescape(document.cookie.substring(c_start,c_end))
        }
    }
    return ""
}

function GetQueryString(name){
    var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if(r!=null)return  decodeURIComponent(r[2]); return null;
}

template.defaults.imports.addUrl = function(value){
    if(value==null||value==""){
        return "img/book.png"
    }else{
        return imgHosturl+value
    }
};
template.defaults.imports.totalReadCount = function(value){
    if(value !== null){
        value = value.toString();
        if(value.length<=4){
            return value;
        }else{
            value = value/10000;
            return value = value.toFixed(1)+"万"
        }
    }
};
template.defaults.imports.topcolor = function(index){
    if(index<3){
        return index+1;
    }else{
        return 4;
    }
};

template.defaults.imports.addFaceUrl = function(value){
    if(value==""||value==null){
        return "img/book.png"
    }else{
        if(checkURL(value)){
            return value;
        }else{
            return imgFaceurl+value
        }
    }
};

function checkURL(str) {
    if (str.match(/(http[s]?|ftp):\/\/[^\/\.]+?\..+\w$/i) == null) {
        return false
    }
    else {
        return true;
    }
}
// 2单本   1书包



function weekTip(text){
    $("#warn").html(text).show();
    setTimeout(function(){
        $("#warn").hide();
    },2000)
}
//免费领取
function limitedTimeFree(unionid,themeid,type){
    $.ajax({
        type:"get",
        url:hostUrl+"order/freetime?channel=weixin&userid="+unionid+"&themeid="+themeid+"&type="+type,
        async:true,
        success:function(data){
            if(data.status==0){
                location.reload();
            }
        }
    });
}

var Q = Query = {
    getFromURL: function(url,parameter){
        var index = url.indexOf("?");
        if (index != -1) {
            var parameterString = url.substr(index + 1);
            var reg = new RegExp("(^|&)" + parameter + "=([^&]*)(&|$)", "i");
            var r = parameterString.match(reg);
            if (r != null){
                return r[2];
            }
        }
        return null;
    },
    get: function(parameter) {
        if (typeof (parameter) == "undefined" || parameter == "") {
            return null;
        }
        var url = window.location.href;
        var index = url.indexOf("?");
        if (index != -1) {
            var parameterString = url.substr(index + 1);
            var reg = new RegExp("(^|&)" + parameter + "=([^&]*)(&|$)", "i");
            var r = parameterString.match(reg);
            if (r != null){
                return r[2];
            }
        }
        return null;
    },
    getInt:function(parameter,defaultValue){
        var value = parseInt(this.get(parameter));
        return isNaN(value) ? (typeof(defaultValue) == "undefined" ? 0 : defaultValue) : value;
    },
    getDecoded:function(parameter){
        return this.decode(this.get(parameter));
    },
    decode:function(srcStr){
        if(typeof(srcStr) == "undefined"){return null;}
        return decodeURIComponent(srcStr);
    },
    encode:function(srcStr){
        if(typeof(srcStr) == "undefined"){return null;}
        return encodeURIComponent(srcStr);
    },
    getSymbol:function(url){
        return url.indexOf("?") == -1 ? "?" : "&";
    },
    joinURL:function(url,queryString){
        return url + this.getSymbol(url) + queryString;
    },
    createQueryString:function(obj){
        var a = [];
        for(var p in obj){
            if(typeof(obj[p]) == "function" || obj[p] == null || typeof(obj[p])=="undefined") continue;
            a.push(p + "=" + obj[p]);
        }
        return a.join("&");
    }
};
	
	